﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using CoolCode.Services;
using CoolCode.Entities;
using CoolCode.Web.UI;

namespace CoolCode.Web.UI
{
    public partial class Menu : BasePage
    { 
        private ModuleList _menuData;

        public ModuleList MenuData
        {
            get
            {
                if (_menuData == null)
                {
                    IMenuService service = ServiceFactory.Produce<IMenuService>();
                    _menuData = service.ListMenu(this.UserName );
                }
                return _menuData;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { 
                BindTree();
            }
        }

        private void BindTree()
        {

            foreach (var menu in MenuData)
            {
                TreeNode tn = new TreeNode
                {
                    Text = menu.Title,
                    SelectAction = TreeNodeSelectAction.Expand
                };
                foreach (var submenu in menu.Children)
                {
                    TreeNode stn = new TreeNode
                    {
                        Text = submenu.Title,
                        SelectAction = TreeNodeSelectAction.Select,
                        Target = submenu.Target ?? "main_right",  
                        NavigateUrl = buildUrl(submenu.ModuleId, submenu.Name)
                         
                    };
                    tn.ChildNodes.Add(stn);
                }
                tvMenu.Nodes.Add(tn);
            }
        }

        protected string buildUrl(object module, object pageId)
        {
            return string.Format("Views/{0}/{1}.aspx", module, pageId);
        }
    }
}
